#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use IO::Socket::INET;
use POSIX qw(setsid);
my $host='127.0.0.1';
my $port=48671;
my $url="http://$host:$port/";
my $root="$FindBin::Bin/../Resources/web";
my %feeds=(hm=>'https://hm-news.co.il/feed/',kore=>'https://www.kore.co.il/flashNews',emess=>'https://www.emess.co.il/allnews',gizra=>'https://hagizra.news/',cat=>'https://black-cat.thechats.click/');
sub launch {
 if(-d '/Applications/Google Chrome.app'){system('/usr/bin/open','-na','Google Chrome','--args',"--app=$url")}
 else{system('/usr/bin/open',$url)}
}
my $server=IO::Socket::INET->new(LocalAddr=>$host,LocalPort=>$port,Listen=>12,ReuseAddr=>1);
unless($server){
 my $peer=IO::Socket::INET->new(PeerAddr=>$host,PeerPort=>$port,Timeout=>2);
 if($peer){print $peer "GET /apple-id HTTP/1.0\r\nHost: $host:$port\r\n\r\n";local $/;my $r=<$peer>;if(($r//'')=~/whatsapp-ai-apple-32\z/){launch();exit}}
 exec('/usr/bin/open','https://wa-ai-apple-yh-32.browncat23.chatgpt.site');
}
my $pid=fork();die unless defined $pid;if($pid){launch();exit}
setsid();
$SIG{CHLD}='IGNORE';
my %mime=(html=>'text/html; charset=utf-8',png=>'image/png',webmanifest=>'application/manifest+json');
while(my $c=$server->accept()){
 my $kid=fork();if(!defined $kid || $kid){close $c; next}
 close $server; $SIG{CHLD}='DEFAULT';alarm 24;
 my $line=<$c>//''; my ($path)=$line=~m{^GET /([A-Za-z0-9./_-]*) HTTP/1\.[01]\r?$};
 my $valid=0;while(my $h=<$c>){last if $h=~/^\r?\n$/;$valid=1 if $h=~/^Host: 127\.0\.0\.1:48671\r?$/i}
 my ($status,$type,$body)=('404 Not Found','text/plain','');
 if($valid && defined $path){
  $path='index.html' if $path eq '';
  if($path eq 'apple-id'){($status,$body)=('200 OK','whatsapp-ai-apple-32')}
  elsif($path=~m{^feed/(\w+)$} && exists $feeds{$1}){
   my $src=$feeds{$1};if(open my $f,'-|','/usr/bin/curl','-fsSL','--proto','=https','--max-time','14','--max-filesize','4000000',$src){local $/;$body=<$f>//'';$status=close($f)?'200 OK':'502 Bad Gateway'}
  }elsif($path=~/^[\w-]+\.(html|png|webmanifest)$/ && -f "$root/$path"){
   $type=$mime{$1};open my $f,'<:raw',"$root/$path" or exit;local $/;$body=<$f>;$status='200 OK';
  }
 }
 binmode $c;print $c "HTTP/1.1 $status\r\nContent-Type: $type\r\nX-Content-Type-Options: nosniff\r\nContent-Length: ".length($body)."\r\nConnection: close\r\n\r\n",$body;close $c;exit;
}
